package com.dliu.javacore.enumFeature;

import java.math.BigDecimal;
import java.util.function.BiFunction;

/**
 * 使用lambda和枚举实现简洁、可读性良好的策略模式
 * @author yanglei
 * date 2021/3/25 11:49
 */
public enum Strategy {
    ADD(BigDecimal::add),
    SUBTRACT(BigDecimal::subtract),
    MULTIPLY(BigDecimal::multiply),
    DOUBLE(Strategy::double2),
    ;

    private final BiFunction<BigDecimal, BigDecimal, BigDecimal> biFunction;

    //加载时调用
    Strategy(BiFunction<BigDecimal, BigDecimal, BigDecimal> biFunction) {
        this.biFunction = biFunction;
    }

    public BigDecimal apply(BigDecimal x, BigDecimal y){
        return biFunction.apply(x, y);
    }

    public static BigDecimal double2(BigDecimal x, BigDecimal y){
        BigDecimal add = x.add(y);
        return add.multiply(new BigDecimal(2));
    }

    //switch 被方法函数替代
//    public BigDecimal apply2(BigDecimal x, BigDecimal y) throws Exception {
//        switch (this){
//            case ADD: return x.add(y);
//            case SUBTRACT: return x.subtract(y);
//            default: throw new Exception("类型异常");
//        }
//    }

    public static void main(String[] args) {
        BigDecimal apply = Strategy.DOUBLE.apply(new BigDecimal(1), new BigDecimal(2));
        BigDecimal sub = Strategy.SUBTRACT.apply(new BigDecimal(8), new BigDecimal(2));
        BigDecimal mul = Strategy.MULTIPLY.apply(new BigDecimal(8), new BigDecimal(2));
        System.out.println(apply);
        System.out.println(sub);
        System.out.println(mul);
    }
}
